<template>
  <div>
    <el-breadcrumb separator-class="el-icon-arrow-right">
      <el-breadcrumb-item :to="{ path: '/home' }">首页</el-breadcrumb-item>
      <el-breadcrumb-item>指标管理</el-breadcrumb-item>
    </el-breadcrumb>
    <el-button icon='el-icon-download' type="primary" @click="exportTemplate">
      导出模板
    </el-button>
    <el-button type="primary" @click="startInsertSimpleTree">
      新增指标
    </el-button>

    <!-- 卡片视图区域 -->
    <el-card>
      <el-table :data="treeList.slice((currentPage-1)*pageSize,currentPage*pageSize)"
                border stripe style="width: 100%">
        <el-table-column label="指标树编号" prop="id" width="200"></el-table-column>
        <el-table-column label="指标树名称" prop="name" width="200"></el-table-column>
        <el-table-column label="指标状态" width="300">
          <template v-slot="scope">
            <el-tag v-if="scope.row.locked" class="isLocked">已归档</el-tag>
            <el-tag v-else class="unLocked">未归档</el-tag>
          </template>
        </el-table-column>
        <el-table-column label="操作">
          <template v-slot="scope">
            <el-button type="info" @click="handleDetail(scope.row.id)">详情</el-button>
            <el-button type="danger" @click="deleteTree(scope.row.id)">删除</el-button>
            <el-button :disabled="scope.row.locked" type="primary" @click="editTree(scope.row.id)">编辑</el-button>
            <el-button :disabled="!scope.row.locked" type="success" @click="dataManage(scope.row.id)">数据管理
            </el-button>
            <el-button v-if="!scope.row.locked" type="warning" @click="locked(scope.row.id)">归档</el-button>
            <el-button v-else type="warning" @click="unlocked(scope.row.id)">取消归档</el-button>
          </template>
        </el-table-column>
      </el-table>

      <!-- 分页区域 -->
      <el-pagination :total="total" background
                     layout="prev, pager, next"
                     @current-change="changeTreeTablePage">
      </el-pagination>
    </el-card>

    <el-dialog
        :visible.sync="insertSimpleTreeDialogVisible"
        title="新增指标结构"
        width="50%"
        @close="endInsertSimpleTree">
      <el-form
          ref="ruleFormRef"
          :model="tree"
          :rules="treeInsertRules"
          label-position='left'
          label-width="100px">
        <el-form-item label="目标账号" prop="userId">
          <el-input v-model="tree.userId" disabled></el-input>
        </el-form-item>
        <el-form-item label="结构名称" prop="name">
          <el-input v-model="tree.name"></el-input>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="endInsertSimpleTree">取 消</el-button>
        <el-button type="primary" @click="insertSimpleTree">录入</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
export default {
  data() {
    return {
      treeList: [],
      total: 0,
      currentPage: 1,//当前页数
      pageSize: 10,//1p十个数据
      insertSimpleTreeDialogVisible: false,//新增结构的页面是否可见
      tree: {
        userId: JSON.parse(window.localStorage.getItem('userInfo')).id,
        name: ""
      },//这是要新增的指标树
      treeInsertRules: {
        name: {
          type: "string",
          required: true,
          trigger: "blur",
          message: "请输入指标结构名称"
        }
      }
    }
  },
  created() {
    this.getAllTrees()
  },
  methods: {
    async getAllTrees() {
      const userInfo = JSON.parse(window.localStorage.getItem('userInfo'))
      const userId = userInfo.id
      // 根据用户id获取所有指标树
      const res = await this.$http.post(`tree/allUnderUser?userId=${userId}`)

      if (res.code !== 200) {
        return this.$message.error('获取指标树列表失败')
      }

      this.treeList = res.data
      this.total = res.data.length
    },
    handleDetail(id) {
      this.$router.push(`treedetial?treeid=${id}`)
    },
    editTree(id) {
      this.$router.push(`treeedit?treeid=${id}`)
    },
    async deleteTree(id) {
      const confirmResult = await this.$confirm('此操作将永久删除该指标树, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).catch(err => err)

      //如果用户确认删除，则返回字符串confirm  错误用catch捕获，返回字符串cancel
      if (confirmResult !== 'confirm') return this.$message.info('已取消删除')

      const res = await this.$http.post(`tree/delete?treeId=${id}`)

      if (res.code !== 200) {
        return this.$message.error('删除指标树失败！')
      }

      this.$message.success(res.message);
      await this.getAllTrees()
    },
    dataManage(id) {
      this.$router.push(`allInstance?treeid=${id}`)
    },
    async locked(id) {
      const res = await this.$http.post(`tree/lock?treeId=${id}`)

      if (res.code === 200) {
        this.$message.success(res.message)
      } else {
        this.$message.error(res.message)
      }


      await this.getAllTrees()
    },
    async unlocked(id) {
      const res = await this.$http.post(`tree/unlock?treeId=${id}`)

      if (res.code === 200) {
        this.$message.success(res.message)
      } else {
        this.$message.error(res.message)
      }

      await this.getAllTrees()
    },
    /**
     * 分页实现函数
     * @param currentPage 新页码
     */
    changeTreeTablePage(currentPage) {
      this.currentPage = currentPage;
    },
    exportTemplate() {
      this.$message.error("待开发");
    },
    startInsertSimpleTree() {
      this.insertSimpleTreeDialogVisible = true;
    },
    /**
     * 插入简单的树
     */
    async insertSimpleTree() {
      await this.$refs.ruleFormRef.validate(async (isValid) => {
        if (!isValid) return;
        const res = await this.$http.post('tree/insert-simple', this.tree);

        if (res.code !== 200) {
          this.endInsertSimpleTree();
          return this.$message.error(res.message);
        }

        this.endInsertSimpleTree();

        await this.getAllTrees();
      });
    },
    endInsertSimpleTree() {
      this.insertSimpleTreeDialogVisible = false;
    }

  }
}
</script>
<style>
.isLocked {
  background-color: #67c23a;
  color: #fff;
}

.unLocked {
  background-color: #c2bf3a;
  color: #fff;
}
</style>